<template>
  <section class="login">
    <Card class="card">
      <validate-form @form-sumit="onFormSumit" class="login-form">
        <validate-input
          type="text"
          :rules="emailrules"
          v-model="emailRef.val"
          labeltext="邮箱:"
        ></validate-input>

        <validate-input
          type="password"
          :rules="passRules"
          v-model="passRef"
          labeltext="密码:"
        ></validate-input>

        <template v-slot:sumit>
          <button type="sumit" class="btn btn-primary sumit-btn">提交</button>
        </template>
      </validate-form>
    </Card>
  </section>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import ValidateForm from "@/components/ValidateForm.vue";
import ValidateInput, { RulesProps } from "@/components/ValidateInput.vue";
import Card from "@/components/Card.vue";
import { useMainStore } from "@/stores/main";
import createMessage from "@/components/CreateMessage";
import { login } from "@/api/api";
const emailrules: RulesProps = [
  { type: "required", message: "cannot be empty" },
  { type: "email", message: "write valid email" },
];
const passRules: RulesProps = [
  { type: "required", message: "can not be empty" },
];
export default defineComponent({
  components: {
    ValidateForm,
    ValidateInput,
    Card,
  },
  setup(prop, context) {
    const emailRef = reactive({
      val: "",
      error: false,
      message: "",
    });
    const store = useMainStore();
    const passRef = ref("");
    const router = useRouter();
    const onFormSumit = async (result: boolean) => {
      if (result) {
        const payload = {
          email: emailRef.val,
          password: passRef.value,
        };
        const res = await login(payload);
        store.login(res);
        createMessage("登录成功跳转回首页", "success");
        router.push("/");
      }
    };
    return {
      emailrules,
      passRules,
      emailRef,
      onFormSumit,
      passRef,
    };
  },
});
</script>

<style lang="scss" scoped>
@import "@/css/common.scss";
.login {
  box-sizing: border-box;
  height: 100%;
  display: flex;
  align-items: center;
}
.card {
  margin-top: 80px;
}
.login-form {
  width: 24rem;
}
.sumit-btn {
  margin-top: 1.5rem;
  width: 100%;
}
</style>
